package com.lzy.filter;

import com.lzy.util.IpUtil;
import com.lzy.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * 请求日志记录过滤器 pre
 *
 * @author G by 2019/9/11 11:50
 */
@Component
@Slf4j
public class RequestLogGlobalGatewayFilterFactory implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("RequestLogGatewayGlobalFilterFactory第二个执行");
        ServerHttpRequest request = exchange.getRequest();
        String uuid = LogUtil.getUuid(request);
        MDC.put("requestId", uuid);
        log.info("请求路径-->{}", request.getURI().getPath());
        log.info("请求IP地址-->{}", IpUtil.getIpAddress(request));
        String token = request.getHeaders().getFirst("Authorization");
        log.info("请求token-->{}", StringUtils.isEmpty(token) ? "" : token);
        log.info("请求的参数如下-->");
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
            log.info("{}-->{}", entry.getKey(), entry.getValue());
        }
        ServerHttpRequest httpRequest = request.mutate().header("uuid", uuid).header("requestId", uuid).build();
        ServerWebExchange webExchange = exchange.mutate().request(httpRequest).build();
        return chain.filter(webExchange);
    }


    @Override
    public int getOrder() {
        return -2;
    }
}
